package main

import (
	"base/app/controller"
	"base/app/models"
	"bytes"
	"crypto/rsa"
	"crypto/x509"
	"errors"
	"fmt"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/xuri/excelize/v2"
	"golang.org/x/crypto/pkcs12"
	"io/ioutil"
	"math"
	"os"
	"strconv"
	"strings"
	"time"
)

func t2() (a int) {
	defer func() {
		a++
	}()
	return 1
}

// 获取1-100所有的质数
func getPrime() []string {
	var arr []string
	for i := 1; i <= 100; i++ {
		if isPrime(i) {
			arr = append(arr, strconv.Itoa(i))
		}
	}
	return arr
}

func isPrime(num int) bool {
	if num < 2 {
		return false
	}
	for i := 2; i < num; i++ {
		if num%i == 0 {
			return false
		}
	}
	return true

}

func BenchmarkStringOperation3() {
	t1 := time.Now().UnixNano()
	strBuf := bytes.NewBufferString("")
	//for i := 0; i < 100000; i++ {
	//	strBuf.WriteString("golang")
	//}

	for _, v := range getPrime() {
		strBuf.WriteString(v)
	}
	result := strBuf.String()
	fmt.Println(result)
	t2 := time.Now().UnixNano()
	fmt.Println((t2 - t1) / 1e6)
}

func GenerateArcCoordinates(centerX, centerY, radius float64, startAngle, endAngle float64, segments int) [][]float64 {
	var arcCoordinates [][]float64

	// 计算每个分段的角度差
	angleStep := (endAngle - startAngle) / float64(segments)

	// 遍历每个分段，计算坐标
	for i := 0; i <= segments; i++ {
		// 计算当前角度
		currentAngle := startAngle + float64(i)*angleStep

		// 计算x和y坐标
		x := centerX + radius*math.Cos(currentAngle)
		y := centerY + radius*math.Sin(currentAngle)*1.15

		// 将坐标添加到结果中
		arcCoordinates = append(arcCoordinates, []float64{x, y})
	}

	return arcCoordinates
}

func main() {

	err := models.InitDb()
	if err != nil {
		fmt.Println("数据库连接失败")
		return
	}
	//fmt.Println(t2())
	//BenchmarkStringOperation3()
	//_ = models.Db.AutoMigrate(&models.Test{})

	r := gin.Default()
	r.Use(cors.New(cors.Config{
		AllowAllOrigins: true,
		//AllowOrigins:     []string{"http://124.70.20.171:2009", "http://39.103.180.154:1001", "http://39.103.180.154:1001", "http://124.70.20.171:888", "http://localhost:4000", "http://localhost:5000", "http://localhost:4050", "http://127.0.0.1:5500", "http://192.168.1.205:4050", "http://www.wzhy.com.cn:8000", "http://192.168.1.205:8000", "http://192.168.1.217:5000", "http://192.168.184.81:5000", "http://127.0.0.1:5500"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Content-Type", "Authorization"},
		AllowCredentials: true,
		MaxAge:           86400,
	}))
	r.GET("/lines", func(c *gin.Context) {
		centerX, centerY := 30.422335935664595, 120.94423155357681 // 圆心坐标
		radius := 0.09                                             // 半径
		//startAngle := math.Pi * 2 * 0.025                          // 起始角度，0 弧度 = 0 度
		//endAngle := math.Pi * 2 * 0.25                             // 终止角度，2π 弧度 = 360 度
		startAngle := math.Pi * 2 * 0.25 // 起始角度，0 弧度 = 0 度
		endAngle := math.Pi * 2 * 0.57
		segments := 100 // 分段数

		coordinates := GenerateArcCoordinates(centerX, centerY, radius, startAngle, endAngle, segments)

		c.JSON(200, gin.H{
			"coordinates": coordinates,
		})
	})
	r.Static("/public", "./public")
	r.POST("/login", controller.Login.Login)
	r.POST("/addRecord", controller.Record.AddRecord)
	r.GET("/getBargeShip", controller.Ship.GetBargeShip)
	r.GET("/getFisherShip", controller.Ship.GetFisherShip)
	r.POST("/getRecordByDateAndState", controller.Record.GetRecordByDateAndState)
	r.POST("/upload", controller.Up.Upload)
	r.POST("/updateRecord", controller.Record.UpdateRecord)
	r.POST("/getDayData", controller.Chart.GetDayData)
	r.POST("/getAreaData", controller.Chart.GetAreaData)
	r.POST("/getShipData", controller.Chart.GetShipData)
	r.POST("/getBargeShipData", controller.Chart.GetBargeShipData)
	r.GET("/getArea", controller.Ship.GetArea)
	r.POST("/getAreaDataByDate", controller.Chart.GetAreaDataByDate)
	r.POST("/getBargeShipDataByDate", controller.Chart.GetBargeShipDataByDate)
	r.POST("/getFisherShipDataByDate", controller.Chart.GetFisherShipDataByDate)
	r.POST("/getCompleteData", controller.Chart.GetCompleteData)
	r.POST("/getTotalData", controller.Chart.GetTotalData)
	r.POST("/getCompleteDataOnly", controller.Chart.GetCompleteDataOnly)
	r.POST("/getAllRecord", controller.Record.GetAllRecord)
	r.POST("/getYesterdayRecord", controller.Record.GetYesterdayRecord)
	r.POST("/getAllDisposalRecord", controller.Record.GetAllDisposalRecord)
	r.POST("/addDisposalRecord", controller.Record.AddDisposalRecord)
	r.POST("/getDisposalRecord", controller.Record.GetDisposalRecord)
	r.POST("/exportDataToExcel", controller.Record.ExportDataToExcel)
	r.POST("/deleteRecordById", controller.Record.DeleteRecordById)
	r.POST("/addFisherShipFile", controller.Manage.AddFisherShip)
	r.POST("/deleteBargeShip", controller.Ship.DeleteBargeShip)
	r.POST("/deleteFisherShip", controller.Ship.DeleteFisherShip)
	r.POST("/addBargeShip", controller.Ship.AddBargeShip)
	r.POST("/addFisherShip", controller.Ship.AddFisherShip)
	r.POST("/deleteUser", controller.Ship.DeleteUser)
	r.POST("/addUser", controller.Ship.AddUser)
	r.GET("/getUser", controller.Ship.GetUser)
	r.POST("/editUser", controller.Ship.EditUser)
	r.Any("/test", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "test",
		})
	})
	r.Run(":1102")
	//r.RunTLS(":1102", "./www.oceanread.net.pem", "./www.oceanread.net.key")
}

// 读取excel文件
func rrr() {
	f, err := excelize.OpenFile("C:\\Users\\chun\\Desktop\\2024崂山水产商会船只明细.xlsx")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()
	// 获取 Sheet1 上所有单元格
	rows, err := f.GetRows("Sheet1")
	if err != nil {
		fmt.Println(err)
		return
	}
	var fisherShips []models.FisherShip
	for idx, row := range rows {
		//if row[0] == "shipname" {
		//	continue
		//}
		//var bargeShip models.BargeShip
		//bargeShip.Name = row[0]
		//bargeShip.MMSI = row[2]
		//
		//fisherShips = append(fisherShips, bargeShip)
		if idx < 2 {
			continue
		}
		var fisherShip models.FisherShip

		fisherShip.Name = strings.ReplaceAll(row[0], " ", "")

		fisherShip.Owner = row[2]
		fisherShip.Kw = row[3]
		fisherShip.Length = row[4]
		fisherShip.MMSI = row[5]
		fisherShip.Northid = row[6]

		fisherShips = append(fisherShips, fisherShip)

	}
	models.Db.Create(&fisherShips)
}

func getPrivateKey(privateKeyName, privatePassword string) (*rsa.PrivateKey, error) {
	f, err := os.Open(privateKeyName)
	if err != nil {
		return nil, err
	}

	bytes, err := ioutil.ReadAll(f)
	if err != nil {
		return nil, err
	}
	// 因为pfx证书公钥和密钥是成对的，所以要先转成pem.Block
	blocks, err := pkcs12.ToPEM(bytes, privatePassword)
	if err != nil {
		return nil, err
	}
	if len(blocks) != 2 {
		return nil, errors.New("解密错误")
	}
	// 拿到第一个block，用x509解析出私钥（当然公钥也是可以的）
	privateKey, err := x509.ParsePKCS1PrivateKey(blocks[0].Bytes)
	if err != nil {
		return nil, err
	}
	return privateKey, nil
}

//	type BargeShip struct {
//		BaseModel
//		Name    string `json:"name"`
//		Northid string `json:"northid"`
//		MMSI    string `json:"mmsi"`
//	}
//
// 根据BargeShip生成用户
//func createBargeShipUser() {
//	var bargeShips []models.BargeShip
//	models.Db.Find(&bargeShips)
//	for _, bargeShip := range bargeShips {
//		var user models.User
//		user.Username = bargeShip.Name
//		user.BargeShip = bargeShip.Name
//		user.Password = "123456"
//		user.Role = "jh"
//
//		models.Db.Create(&user)
//
//	}
//
//}

//type FisherShip struct {
//	BaseModel
//	Name    string `json:"name"`
//	Owner   string `json:"owner"`
//	Kw      string `json:"kw"`
//	Length  string `json:"length"`
//	MMSI    string `json:"mmsi"`
//	Northid string `json:"northid"`
//}

// 根据FisherShip生成用户
func createFisherShipUser() {
	var fisherShips []models.FisherShip
	models.Db.Find(&fisherShips)
	fisherArr := make([]string, 0)
	for _, fisherShip := range fisherShips {
		//var user models.User
		//user.Username = fisherShip.Name
		//user.FisherShip = fisherShip.Name
		//user.Password = "123456"
		//user.Role = "ym"

		//models.Db.Create(&user)
		fisherArr = append(fisherArr, fisherShip.Name)

	}
	var user models.User
	user.Username = "崂山区水产商会"
	user.Password = "lly123456"
	user.Role = "ym"
	user.FisherShip = strings.Join(fisherArr, ",")
	models.Db.Create(&user)
}

//遍历所有的record 去掉Name中所有的空格
//func trimFisherShipName() {
//	var records []models.Record
//	models.Db.Find(&records)
//	for _, fisherShip := range records {
//		models.Db.Model(&fisherShip).Update("fisher_ship", strings.ReplaceAll(fisherShip.FisherShip, " ", ""))
//	}
//}
//鲁城渔60167
//鲁城渔60577
//鲁城渔60968
//鲁城渔60333
//鲁城渔60157
//鲁城渔60868
//鲁城渔60586
//鲁城渔60039
//鲁城渔60165
//鲁城渔60069
//鲁城渔60131
//鲁城渔60598
//鲁城渔60170
//鲁城渔60182
//鲁城渔60008
//鲁城渔60129
//鲁城渔60089
//鲁城渔60099
//鲁城渔60001
//鲁城渔60002
//鲁城渔60893
//鲁城渔60188
//鲁城渔60098
//鲁城渔60056
//鲁城渔60058
//鲁城渔60085
//鲁城渔60518
//鲁城渔60768
//鲁城渔60077
//鲁城渔60130
//鲁城渔60517
//鲁城渔60195
//鲁城渔60109
//鲁城渔60078
//鲁城渔60196
//鲁城渔60578
//鲁城渔60009
//鲁城渔60116
//鲁城渔运60097
//鲁城渔60877

func sss() {
	//	添加fisherShip
	arr := []string{"鲁城渔60167", "鲁城渔60577", "鲁城渔60968", "鲁城渔60333", "鲁城渔60157", "鲁城渔60868", "鲁城渔60586", "鲁城渔60039", "鲁城渔60165", "鲁城渔60069", "鲁城渔60131", "鲁城渔60598", "鲁城渔60170", "鲁城渔60182", "鲁城渔60008", "鲁城渔60129", "鲁城渔60089", "鲁城渔60099", "鲁城渔60001", "鲁城渔60002", "鲁城渔60893", "鲁城渔60188", "鲁城渔60098", "鲁城渔60056", "鲁城渔60058", "鲁城渔60085", "鲁城渔60518", "鲁城渔60768", "鲁城渔60077", "鲁城渔60130", "鲁城渔60517", "鲁城渔60195", "鲁城渔60109", "鲁城渔60078", "鲁城渔60196", "鲁城渔60578", "鲁城渔60009", "鲁城渔60116", "鲁城渔运60097", "鲁城渔60877"}
	for _, v := range arr {
		var fisherShip models.FisherShip
		fisherShip.Name = v
		fisherShip.SeaArea = "城阳区"
		models.Db.Create(&fisherShip)
	}

}

func readDir() {
	//	读取 ./public/img/output/wave 下的所有文件夹
	files, _ := ioutil.ReadDir("./public/img/output/wind")
	for _, file := range files {
		fmt.Println(file.Name())
		//2024061000
		day := file.Name()[6:8]
		dayNum, _ := strconv.Atoi(day)
		if dayNum < 20 {
			dayNum += 7
		}
		day = strconv.Itoa(dayNum)
		hour := file.Name()[8:10]
		//	改名为2024+06+(day+10)+hour
		_ = os.Rename("./public/img/output/wind/"+file.Name(), "./public/img/output/wind/202406"+day+hour)
	}
}
